package repositories

import (
	"gitee.com/tq1024/wechat-sdk-go/dbconnect"
	"strings"
)

type OfficialAccount struct {
	tableName string
}

var OfficialAccountRepository OfficialAccount

func init() {
	OfficialAccountRepository = OfficialAccount{
		"official_accounts",
	}
}

func (oa OfficialAccount) GetByAppId(appId string) (map[string]interface{}, error) {

	sql := "select * from `" + oa.tableName + "` where `appid` = ?"

	return dbconnent.GetFirstRecord(sql, appId)

}

func (oa OfficialAccount) Add(data map[string]string) (int64, error) {

	var valueSeps, fields string

	keyLen := len(data)

	values := make([]interface{}, keyLen)

	i := 0

	for key, val := range data {
		valueSeps += "?,"
		fields += "`" + key +"`,"
		values[i] = val

		i++
	}

	fieldStr := strings.TrimRight(fields, ",")
	valueSeps = strings.TrimRight(valueSeps, ",")

	sql := "insert into `" + oa.tableName + "` (" + fieldStr + ") values (" + valueSeps + ")"

	result, err := dbconnent.Exec(sql, values...)

	if nil != err {

		return 0, err

	}

	count, err := result.RowsAffected()

	if nil != err {
		return 0, err
	}

	return count, nil

}
